package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;

@Service
public class SafetyService {

    @Autowired
    private ResourceConsumerService resourceConsumerService;

    @Value("${app.safety.max-memory-percent:85}")
    private int maxMemoryPercent;

    @Value("${app.safety.max-system-load:80}")
    private double maxSystemLoad;

    @Value("${app.safety.check-interval:30000}")
    private long checkInterval;

    private OperatingSystemMXBean osBean;
    private MemoryMXBean memoryBean;
    private boolean safetyEnabled = true;

    @PostConstruct
    public void init() {
        this.osBean = ManagementFactory.getOperatingSystemMXBean();
        this.memoryBean = ManagementFactory.getMemoryMXBean();
        System.out.println("安全监控服务已启动");
        System.out.println("最大内存使用率: " + maxMemoryPercent + "%");
        System.out.println("最大系统负载: " + maxSystemLoad + "%");
    }

    @Scheduled(fixedDelayString = "${app.safety.check-interval:30000}")
    public void performSafetyCheck() {
        if (!safetyEnabled) {
            return;
        }

        try {
            // 检查内存使用率
            long usedMemory = memoryBean.getHeapMemoryUsage().getUsed();
            long maxMemory = memoryBean.getHeapMemoryUsage().getMax();
            int memoryUsagePercent = (int) ((usedMemory * 100) / maxMemory);

            // 检查系统负载
            double systemLoad = osBean.getSystemLoadAverage();
            int availableProcessors = osBean.getAvailableProcessors();
            double systemLoadPercent = (systemLoad / availableProcessors) * 100;

            // 记录当前状态
            System.out.println("安全检查 - 内存使用: " + memoryUsagePercent + "%, 系统负载: " + 
                             String.format("%.1f", systemLoadPercent) + "%");

            // 内存使用率过高
            if (memoryUsagePercent > maxMemoryPercent) {
                System.err.println("⚠️ 警告：内存使用率过高 (" + memoryUsagePercent + "% > " + maxMemoryPercent + "%)");
                System.err.println("建议：考虑减少内存分配或增加JVM堆内存");
            }

            // 系统负载过高
            if (systemLoadPercent > maxSystemLoad) {
                System.err.println("⚠️ 警告：系统负载过高 (" + String.format("%.1f", systemLoadPercent) + 
                                 "% > " + maxSystemLoad + "%)");
                System.err.println("建议：考虑降低CPU利用率设置");
            }

            // 极端情况：自动降级
            if (memoryUsagePercent > 95) {
                System.err.println("🚨 紧急：内存使用率达到 " + memoryUsagePercent + "%，触发保护机制");
                triggerEmergencyProtection();
            }

        } catch (Exception e) {
            System.err.println("安全检查失败: " + e.getMessage());
        }
    }

    private void triggerEmergencyProtection() {
        System.err.println("🛡️ 激活紧急保护模式...");
        // 可以在这里添加紧急保护逻辑，比如：
        // 1. 停止资源消耗服务
        // 2. 强制GC
        // 3. 发送告警
        
        System.gc(); // 强制垃圾回收
        System.err.println("已执行强制垃圾回收");
    }

    public void setSafetyEnabled(boolean enabled) {
        this.safetyEnabled = enabled;
        System.out.println("安全监控 " + (enabled ? "已启用" : "已禁用"));
    }

    public boolean isSafetyEnabled() {
        return safetyEnabled;
    }

    public String getSafetyStatus() {
        long usedMemory = memoryBean.getHeapMemoryUsage().getUsed();
        long maxMemory = memoryBean.getHeapMemoryUsage().getMax();
        int memoryUsagePercent = (int) ((usedMemory * 100) / maxMemory);
        
        double systemLoad = osBean.getSystemLoadAverage();
        int availableProcessors = osBean.getAvailableProcessors();
        double systemLoadPercent = (systemLoad / availableProcessors) * 100;

        return String.format(
            "安全监控: %s, 内存使用: %d%% (阈值: %d%%), 系统负载: %.1f%% (阈值: %.0f%%)",
            safetyEnabled ? "启用" : "禁用",
            memoryUsagePercent, maxMemoryPercent,
            systemLoadPercent, maxSystemLoad
        );
    }
} 